package com.semidata.rtd.core.log;

import java.io.FileOutputStream;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

import com.semidata.rtd.core.service.SendableService;

public class LogBlockHandler implements SendableService<LogBlock>{
	
	private boolean quit = false;
	private LinkedBlockingQueue<LogBlock> queue = new LinkedBlockingQueue<>();
	private Thread thread = null;

	@Override
	public void send(LogBlock block) {
		try {
			queue.put(block);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	
	@Override
	public void start() {
		
		thread = new Thread(new Runnable() {

			@Override
			public void run() {
				while (true) {
					try {
						LogBlock block = queue.poll(1, TimeUnit.SECONDS);
						if (block == null) {
							if (quit)
								break;
							else
								continue;
						}
						FileOutputStream out = new FileOutputStream(block.getPath(), true);
						out.write(block.getBytes(), 0, block.size());
						out.close();
					} catch (Exception e) {
					}
				}
			}
			
		});
		thread.start();
	}

	@Override
	public void stop() {
		quit = true;
		try {
			if (thread != null)
				thread.join();
		} catch (InterruptedException e) {
		}
		
	}
}
